package com.chun.interceptor;

import com.alibaba.fastjson2.JSON;
import com.chun.pojo.Result;
import com.chun.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasLength(token)) {
            log.info("没有令牌");
            Result notLogin = Result.error("Not_Login");
            String jsonString = JSON.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
            return false;
        }
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌有误");
            Result notLogin = Result.error("Not_Login");
            String jsonString = JSON.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonString);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行afterCompletion");
    }
}
